import {Injectable} from '@angular/core';
import {JPush} from "@jiguang-ionic/jpush";
import {DeviceService} from "../device/device.service";

@Injectable()
export class JPushControlerService {

    private sequence: number = 0;
    private isOnCordova: boolean = false;
    private timer: any;// 设置别名定时器


    constructor(private jPush: JPush,
                private deviceService: DeviceService) {
        this.isOnCordova = this.deviceService.isOnCordova();
    }

    public init() {
        if (!this.isOnCordova) return;

        this.jPush.init();
    }

    public stopPush(){
        if (!this.isOnCordova) return;

        this.jPush.stopPush();
    }

    public resumePush(){
        if (!this.isOnCordova) return;

        this.jPush.resumePush();
    }

    public setRegistrationIDLocalStorage() {
        if (!this.isOnCordova) return;

        this.jPush.getRegistrationID().then(value => {
            localStorage.setItem('RegistrationID', value);
        }, reason => {
            localStorage.setItem('RegistrationID', reason);
        });
    }

    public getRegistrationIDLocalStorage() {
        return localStorage.getItem('RegistrationID') || '';
    }

    /**
     * 清除应用通知角标
     * app唤醒时
     */
    public clearBadge() {
        if (!this.isOnCordova) return;

        this.jPush.setApplicationIconBadgeNumber(0);
        this.jPush.resetBadge();
    }

    /**
     * 设置别名为业务上收不到推送的值
     * 网络连接时检测到此方法失败时
     * 点击退出按钮时&&首次安装进入登录页时&&自动退出到登录页时（自动退出到指纹登录或者手势登录时?）===登录页加载时
     */
    public setAliasNull() {
        if (!this.isOnCordova) return;

        this.sequence++;
        this.jPush.setAlias({sequence: this.sequence, alias: 'logout'}).then(value => {
            localStorage.setItem('stopPush', 'OK');
        }, reason => {
            localStorage.setItem('stopPush', 'fail');
        }).catch(reason => {
            localStorage.setItem('stopPush', 'fail');
        });
        localStorage.setItem('SetAlias', 'logout');
    }

    /**
     * 设置别名为用户名
     * 首页加载时
     */
    private setAliasUserName() {
        if (!this.isOnCordova) return;

        if (localStorage.getItem('SetAlias') !== 'OK' && localStorage.getItem('userName')) {
            let userCode = localStorage.getItem('userName').trim().replace(" ", "_").toUpperCase();
            this.sequence++;
            this.jPush.setAlias({sequence: this.sequence, alias: userCode}).then(value => {
                console.log('setAlias ok', value);
                localStorage.setItem('SetAlias', 'OK');
                localStorage.removeItem('stopPush');
                this.stopSetAlias();
            }).catch(err => {
                console.log('setAlias catch', err);
                localStorage.setItem('SetAlias', 'ERR');
            })
        }
    }


    public intervalSetAlias() {
        this.timer = setInterval(()=>this.setAliasUserName(), 3000)
    }

    private stopSetAlias() {
        clearInterval(this.timer);
        this.timer = null;
    }
}
